﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Smart.Data.Model
{
    public class DataTableModel
    {
        public DataTableModel(DataHelper helper)
        {
            Helper = helper;
        }

        protected DataHelper Helper { get; set; }

        public string TableName { get; set; }
        public string PrimaryKey { get; set; }

        public DataTable Query(params string[] filters)
        {
            var sql = string.Format(ModelConstans.SelectAllFieldFromTable, TableName) + BuildFilter(filters);
            return Helper.Create(sql, TableName);
        }

        public void Update(DataTable data)
        {
            var sql = string.Format(ModelConstans.SelectAllFieldFromTable, TableName);
            Helper.Update(data, sql);
        }

        public void UpdateWithFilter(DataTable data, string[] filters)
        {
            var source = Query(filters);
            source.PrimaryKey = new DataColumn[] { source.Columns[PrimaryKey] };
            data.PrimaryKey = new DataColumn[] { data.Columns[PrimaryKey] };

            foreach (var d in data.AsEnumerable())
            {
                var dataRow = source.Rows.Find(d[PrimaryKey]);

                if (dataRow == null)
                {
                    source.Rows.Add(d.ItemArray);
                }
                else
                {
                    dataRow.ItemArray = d.ItemArray;
                }
            }

            Helper.Update(source, string.Format(ModelConstans.SelectAllFieldFromTable, TableName));

        }

        public void Delete(string[] filters)
        {
            var sql = string.Format(ModelConstans.DeleteFromTable, TableName) + BuildFilter(filters);
            Helper.ExecuteNonQuery(sql);
        }

        public object Compute(string cmd, string column, params string[] filters)
        {
            var sql = string.Format(ModelConstans.SelectFieldFromTable, string.Format("{0}({1})", cmd, column), TableName) + BuildFilter(filters);
            return Helper.ExecuteScalar(sql);

        }

        string BuildFilter(string[] filters)
        {
            if (filters == null || filters.Length == 0)
                return string.Empty;

            var builder = new StringBuilder(ModelConstans.Where);
            foreach (var f in filters)
            {
                builder.AppendLine(f);
            }
            return builder.ToString();
        }
    }
}
